'use strict'

module.exports = core
// require: .js/.json/.node
// .js ->module.exports/exports
// .json ->json.parse
// any ->.js
const fs = require('fs')
const path = require('path')
const semver = require('semver')
const colors = require('colors/safe')
const userHome = require('user-home')
const pkg = require('../package.json')
const commander = require('commander')

const log = require('@djun-cli/log')
const init = require('@djun-cli/init')
const exec = require('@djun-cli/exec')
const { LOWEST_NODE_VERSION, DEFAULT_CLI_HOME, NPM_NAME, DEPENDENCIES_PATH } = require('../lib/const')

let config
const program = new commander.Command()

async function core() {
  try {
    await prepare()
    registerCommander()
  } catch (e) {
    log.error(e.message)
  }
}

function registerCommander() {
  // 提示help
  program
    .name(Object.keys(pkg.bin)[0])
    .usage('<command> [options]')
    .version(pkg.version)
    .option('-d, --debug', '是否打开调试模式', false)
    .option('-tp, --targetPath <targetPath>', '是否指定本地调试文件路径', '')

  program.command('init [projectName]').option('-f, --force', '是否强制初始化项目').action(exec)

  // 开启debug模式
  program.on('option:debug', function () {
    if (program.debug) {
      process.env.LOG_LEVEL = 'verbose'
    } else {
      process.env.LOG_LEVEL = 'info'
    }
    log.level = process.env.LOG_LEVEL
  })

  // 对未知命令监听
  program.on('command:*', function (obj) {
    const availableCommands = program.commands.map((cmd) => cmd.name())
    console.log(colors.red('未知的命令：' + obj[0]))
    if (availableCommands.length > 0) {
      console.log(colors.red('可用命令：' + availableCommands.join(',')))
    }
  })

  // 指定targetPath
  program.on('option:targetPath', function () {
    process.env.CLI_TARGET_PATH = program.targetPath
  })

  // console.log(process.argv);

  if (process.argv && process.argv.length < 1) {
    program.outputHelp()
    console.log()
  }
  program.parse(process.argv)
}

// 初始化
async function prepare() {
  checkPkgVersion()
  checkRoot()
  checkUserHome()
  checkEnv()
  await checkGlobalUpdate()
}

// 检查 cli 最新版本
async function checkGlobalUpdate() {
  log.verbose('检查 imooc-cli 最新版本')
  const { getNpmSemverVersion } = require('@djun-cli/get-npm-info')
  const currentVersion = pkg.version
  const npmName = pkg.name
  const lastVersion = await getNpmSemverVersion(currentVersion, npmName)
  log.verbose('lastVersion:', lastVersion)
  if (lastVersion && semver.gt(lastVersion, currentVersion)) {
    log.warn(
      colors.yellow(`请手动更新 ${NPM_NAME}，当前版本：${currentVersion}，最新版本：${lastVersion}
                更新命令： npm install -g ${NPM_NAME}`)
    )
  }
}

// 检查环境变量
function checkEnv() {
  log.verbose('开始检查环境变量')
  const dotenv = require('dotenv')
  config = dotenv.config({
    path: path.resolve(userHome, '.env'),
  })
  config = createCliConfig() // 准备基础配置
  log.verbose('环境变量', config)
}

// 返回配置
function createCliConfig() {
  const cliConfig = {
    home: userHome,
  }
  if (process.env.CLI_HOME) {
    cliConfig['cliHome'] = path.join(userHome, process.env.CLI_HOME)
  } else {
    cliConfig['cliHome'] = path.join(userHome, DEFAULT_CLI_HOME)
  }
  process.env.CLI_HOME_PATH = cliConfig.cliHome
  return cliConfig
}

// 检查用户主目录
function checkUserHome() {
  if (!userHome || !fs.existsSync(userHome)) {
    throw new Error(colors.red('当前登录用户主目录不存在！'))
  }
}

// 检查root启动
function checkRoot() {
  const rootCheck = require('root-check')
  rootCheck(colors.red('请避免使用 root 账户启动本应用'))
}



// 检查脚手架版本
function checkPkgVersion() {
  log.verbose('version:', pkg.version)
}
